<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon icon="ep:promotion" size="18" style="margin-right: 5px;"></SvgIcon>
        <span>{{ dialogTitle }}</span>
      </div>
    </template>

    <el-steps :active="stepsActive" simple style="margin-bottom: 15px">
      <el-step icon="UploadFilled" title="上传应用"></el-step>
      <el-step icon="Edit" title="更新说明"></el-step>
      <el-step icon="Promotion" title="发布应用"></el-step>
    </el-steps>

    <!-- 应用上传操作 -->
    <template v-if="stepsActive === 1">
      <UploadFile v-model="formData.download_url" :file-size="256" :file-type="['.ipa', '.apk']" upload-path="app" @app-info="handlePkgInfo" @file-info="handleFileUploadSuccess"/>
    </template>

    <!-- 更新说明 -->
    <template v-if="stepsActive === 2">
      <el-input v-model="formData.message" :autosize="{ minRows: 5}" placeholder="请输入更新说明" type="textarea"/>
    </template>

    <template v-if="stepsActive === 3">

      <el-alert v-if="appInfo.id <= 0" :closable="false" class="alert-first-margin" title="请完善App应用信息" type="info"/>

      <el-form v-if="appInfo.id <= 0"
               ref="appFormRef"
               v-loading="dataLoading"
               :model="appInfo"
               :rules="appInfoRules"
               class="full-form"
               label-width="100px"
               status-icon>

        <el-form-item label="应用名称：" prop="name">
          <el-input v-model="appInfo.name" placeholder="请输入应用名称"/>
        </el-form-item>

        <el-form-item label="Identifier：" prop="bundle_id">
          <el-input v-model="appInfo.bundle_id" placeholder="请输入Identifier" readonly/>
        </el-form-item>

        <el-form-item label="应用类型：" prop="type">
          <el-radio-group v-model="appInfo.type">
            <el-radio :value="0">Android</el-radio>
            <el-radio :value="1">iOS</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="应用图标：" prop="icon_url">
          <el-input v-model="appInfo.icon_url" :autosize="{ minRows: 1}" placeholder="请输入链接地址或点击下方进行上传" style="margin-bottom: 5px" type="textarea"/>
          <UploadImage v-model="appInfo.icon_url" :show-delete="true" upload-path="app"/>
        </el-form-item>

        <el-form-item label="应用介绍：" prop="description">
          <el-input v-model="appInfo.description" :autosize="{ minRows: 2}" placeholder="请输入应用介绍" type="textarea"/>
        </el-form-item>
      </el-form>

      <el-alert :closable="false" class="alert-first-margin" title="应用版本信息" type="info"/>

      <!-- 表单数据 -->
      <el-form ref="formRef"
               v-loading="dataLoading"
               :model="formData"
               :rules="formRules"
               class="full-form"
               label-width="100px"
               status-icon>

        <el-form-item label="版本号：" prop="code">
          <el-input v-model="formData.code" placeholder="请输入版本号" readonly/>
        </el-form-item>

        <el-form-item label="更新说明：" prop="message">
          <el-input v-model="formData.message" :autosize="{ minRows: 3}" placeholder="请输入更新说明" type="textarea"/>
        </el-form-item>

        <el-form-item label="下载地址：" prop="download_url">
          <el-input v-model="formData.download_url" :autosize="{ minRows: 1}" placeholder="应用下载地址" readonly type="textarea"/>
        </el-form-item>

        <el-form-item label="强制更新：">
          <el-switch v-model="formData.force_update" active-text="开启" inactive-text="关闭" inline-prompt/>
        </el-form-item>

        <el-form-item label="是否显示：">
          <el-switch v-model="formData.enabled" active-text="显示" inactive-text="隐藏" inline-prompt/>
        </el-form-item>
      </el-form>
    </template>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="stepsActive == 2" type="success" @click="nextSteps()">下一步</el-button>
        <el-button v-if="stepsActive == 3" :loading="dataLoading" type="primary" @click="onSubmitForm()">确定发布</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { UploadFile, UploadImage } from '@/components/upload';
import { appDetail, appSaveOrUpdate, appVersionPublish, defAppInfo } from '@/api/api-app.ts';

defineOptions({name: 'app-publish-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false);// 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

export type PublishData = {
  app_name: string;
  app_type: number;
  app_bundle_id: string;
  code: string;
  message: string;
  file_size: number;
  download_url: string;
  force_update: boolean;
  enabled: boolean;
}

const defaultForm: PublishData = <PublishData>{force_update: true, enabled: true, download_url: ''};

// 表单数据
const formData = ref({...defaultForm});
const appInfo = ref({...defAppInfo});
const stepsActive = ref(1);
const nextSteps = () => stepsActive.value++;

// 表单验证规则
const formRules = reactive<FormRules>({
  code: [{required: true, message: '请输入版本号', trigger: 'blur'}],
  message: [{required: true, message: '请输入更新说明', trigger: 'blur'}],
  download_url: [{required: true, message: '请上传应用程序', trigger: 'blur'}],
});

// 表单验证规则
const appInfoRules = reactive<FormRules>({
  type: [{required: true, message: '请选择 App 类型', trigger: 'blur'}],
  name: [{required: true, message: '请输入应用名称', trigger: 'blur'}],
  bundle_id: [{required: true, message: '请输入Identifier', trigger: 'blur'}],
  icon_url: [{required: true, message: '请上传应用图标', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 打开弹窗 */
const open = async () => {
  dialogTitle.value = 'App应用发布';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();
}
// 提供 open 方法，用于打开弹窗
defineExpose({open})

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  let message = formData.value.message
  if (!message || message.trim().length === 0) {
    ElMessage({type: 'warning', message: '请输入更新说明'})
    return
  }
  // 如果应用已创建
  if (appInfo.value.id > 0) {
    await handleAppVersionPublish();
  } else {
    await formRef.value?.validate((valid, fields) => {
      if (!valid) {
        ElMessage({type: 'error', message: '请检查是否已完善App应用信息',});
        return
      }
      const loading = ElLoading.service({
        lock: true,
        text: '正在创建应用...',
        background: 'rgba(0, 0, 0, 0.2)'
      })
      // 提交数据
      appSaveOrUpdate(appInfo.value, true).then(response => {
        // 发布版本信息
        handleAppVersionPublish();
      }).finally(() => loading.close())

    });
  }
};

/** 处理应用版本发布 */
const handleAppVersionPublish = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    appVersionPublish(formData.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  stepsActive.value = 1;
  appInfo.value = {...defAppInfo};
  appInfo.value.id = 0;
  appInfo.value.enabled = true;
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

/** 处理应用解析信息 */
const handlePkgInfo = (pkgInfo: any, extension: string) => {
  // console.log('handlePkgInfo =>')
  // console.log(pkgInfo)
  // console.log(extension)

  if (extension !== 'apk' && extension !== 'ipa') return;

  if (extension === 'apk') {
    formData.value.app_type = 0
    let label = pkgInfo.application.label || []
    formData.value.app_name = label.length > 0 ? label[0] : ''
    formData.value.app_bundle_id = pkgInfo.package
    formData.value.code = pkgInfo.versionName
  } else if (extension === 'ipa') {
    formData.value.app_type = 1
    formData.value.app_name = pkgInfo.CFBundleDisplayName
    formData.value.app_bundle_id = pkgInfo.CFBundleIdentifier
    //formData.value.code = pkgInfo.CFBundleVersion
    formData.value.code = pkgInfo.CFBundleShortVersionString
  }

  let params = {
    type: formData.value.app_type,
    bundleId: formData.value.app_bundle_id,
  }
  // 获取应用信息
  appDetail(params).then(response => {
    let data = response.data
    let exist = data.exist || 0
    if (exist > 0) {
      appInfo.value = data.info
    } else {
      appInfo.value.id = 0;
      appInfo.value.name = formData.value.app_name;
      appInfo.value.type = formData.value.app_type;
      appInfo.value.bundle_id = formData.value.app_bundle_id;
      appInfo.value.enabled = true;
    }
  });
};

/** 文件上传成功后触发 */
const handleFileUploadSuccess = (file: any) => {
  formData.value.file_size = file.size;
  nextSteps();
}

</script>

<style lang="scss" scoped>

</style>
